package com.lhs.aopcache.processor;

import com.lhs.aopcache.base.CacheMetadata;
import com.lhs.aopcache.exception.AopCacheException;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 缓存获取操作
 */
public class AopCacheGetProcessor extends AbstractAopCacheProcessor {

    @Override
    public boolean doPreProcess(CacheMetadata metadata, MethodInvocation invocation) {
        return false;
    }

    @Override
    public Object endProcessor(CacheMetadata metadata, MethodInvocation invocation) {
        try {
            String group = metadata.getGroup();
            String keys = metadata.getKeys();
            String[] keyArray = keys.split(SPLIT_KEY);
            Object result;
            for (String key : keyArray) {
                result = getAopCache().get(group, key);
                if (result != null) {
                    return result;
                }
            }
            result = invocation.proceed();
            if (result != null) {
                for (String key : keyArray) {
                    getAopCache().put(group, key, result);
                }
            }
            return result;
        } catch (Throwable e) {
            throw new AopCacheException(e);
        }
    }
}
